package cn.cvs.controller;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleService;
import cn.cvs.service.SysUserService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.*;

@Controller
@RequestMapping("/user")
//@Scope("prototype")
public class SysUserController {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;

    private Logger logger = Logger.getLogger(SysUserController.class);
    private ArrayList<SysUser> sysUserList = new ArrayList<>();

    // 用于返回查询到的用户数据
    private ArrayList<SysUser> queryUserList = new ArrayList<>();

    public SysUserController(){
        try{
            sysUserList.add(new SysUser(5,"zhaojing","赵静","5555555",1,"13354784445","上海市宝山区",1,1,new Date(),1,new Date()));
            sysUserList.add(new SysUser(4,"wanglin","王琳","5555555",1,"13354784445","上海市宝山区",1,1,new Date(),1,new Date()));
            sysUserList.add(new SysUser(1,"test001","测试用户001","5555555",1,"13354784445","上海市宝山区",1,1,new Date(),1,new Date()));
            sysUserList.add(new SysUser(2,"zhaoyan","赵燕","5555555",1,"13354784445","上海市宝山区",1,1,new Date(),1,new Date()));
            sysUserList.add(new SysUser(3,"test003","测试用户003","5555555",1,"13354784445","上海市宝山区",1,1,new Date(),1,new Date()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 查询所有用户
    //@GetMapping("/list")
    public String list(Model model){
        logger.info("当查询条件为空时,查询用户信息!");
        queryUserList.clear();
        queryUserList.addAll(sysUserList);
        model.addAttribute("queryUserList",queryUserList);
        return "sysUser/sysUserList";
    }

    // 根据条件查询部分用户
    //@PostMapping("/list")
    public String list(@RequestParam(value = "realName", required = false) String realName, Model model){
        logger.info("查询条件:[realName] = " + realName + ", 查询用户信息");
        queryUserList.clear();
        if (null != realName && !"".equals(realName)){
            for (SysUser user : sysUserList){
                if (user.getRealName().indexOf(realName) != -1){
                    queryUserList.add(user);
                }
            }
        }else{
            queryUserList.addAll(sysUserList);
        }
        model.addAttribute("queryUserList",queryUserList);
        return "sysUser/sysUserList";
    }

    // 跳转到登录页面
    //@RequestMapping(value = "/toLogin")
    public String login(){
        logger.debug("跳转到登录页面");
        return "login";
    }

    // 登录
    @PostMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session,
                          @RequestParam String account,
                          @RequestParam String password) throws Exception {
        logger.debug("登录方法");
        // 调用service方法,进行用户匹配
        SysUser sysUser = sysUserService.login(account, password);
        SysUser selectAccountExist = sysUserService.getByAccount(account);
        if (null != sysUser){
            // 将登录的用户放入session
            session.setAttribute(Constants.USER_SESSION, sysUser);
            return "redirect:/user/toMain";
            // response.sendRedirect("jsp/frame.jsp");
        }else if (null == selectAccountExist){
            request.setAttribute("error","用户名不存在");
            return "login";
        }else{
            // 页面跳转(login.jsp)带出提示信息--转发
            request.setAttribute("error","用户名或密码不正确");
            return "login";
        }
    }

    // 跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session){
        if (session.getAttribute(Constants.USER_SESSION) == null){
            // 重定向到登录页面接口
            return "redirect:/user/toLogin";
        }
        return "frame";
    }

    // 退出登录
    @RequestMapping(value = "/toLogin")
    public String returnLogin(HttpSession session){
        logger.debug("退出登录");
        session.invalidate();
        return "login";
    }

    // 捕获异常信息,跳转到error页面
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest request){
        String ex = e.getMessage();
        request.setAttribute("error",e.getMessage());
        return "login";
    }

    // 一个抛出异常的接口
    @RequestMapping("/exLogin")
    public String exLogin(HttpSession session,
                          @RequestParam String account,
                          @RequestParam String password) throws Exception {
        SysUser sysUser = sysUserService.login(account, password);
        SysUser selectAccountExist = sysUserService.getByAccount(account);
        if (null != sysUser){
            // 将登录的用户放入session
            session.setAttribute(Constants.USER_SESSION, sysUser);
            return "redirect:/user/toMain";
            // response.sendRedirect("jsp/frame.jsp");
        }else if (null == selectAccountExist){
            throw new RuntimeException("用户名不存在!");
        }else{
            // 页面跳转(login.jsp)带出提示信息--转发
            throw new RuntimeException("用户名或密码不正确!");
        }
    }

    @GetMapping("/list")
    public String getUserList(Model model, String queryRealName, Integer queryRoleId,
                              @RequestParam(defaultValue = "1") Integer pageIndex){
        List<SysUser> userList = null;
        try{
            // 设置页面容量
            int pageSize = Constants.pageSize;
            // 总数量(表)
            int totalCount = sysUserService.getUserCount(queryRealName,queryRoleId);
            // 总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            // 控制首页和尾页
            if (pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            userList = sysUserService.getUserList(queryRealName,queryRoleId,pageIndex,pageSize);
            model.addAttribute("userList",userList);
            List<SysRole> roleList = null;
            roleList = sysRoleService.getRoleList();
            model.addAttribute("roleList",roleList);
            model.addAttribute("queryRealName",queryRealName);
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("用户列表访问失败!");
            return "redirect:/toSysError";
        }
        return "sysUser/list";
    }

    // 跳转到异常处理页面
    @RequestMapping(value = "/toSysError")
    public String sysError(){
        return "sysError";
    }

    // 跳转到用户添加页面
    @GetMapping("/toAdd")
    public String getAdd(Model model){
        logger.info("跳转至用户添加页面");
        List<SysRole> sysRoleList = new ArrayList<>();
        try{
            sysRoleList = sysRoleService.getRoleList();
            model.addAttribute("sysRoleList",sysRoleList);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "sysUser/add";
    }

    // 添加用户不包括文件上传
    /*
    @PostMapping("/add")
    public String add(SysUser sysUser, HttpSession session) throws Exception {
        sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        if (sysUserService.add(sysUser)){
            return "redirect:/user/list";
        }
        return "redirect:/add";
    }*/

    // 添加用户包括单文件上传
    /*@PostMapping("/add")
    public String add(SysUser sysUser, HttpSession session, HttpServletRequest request,
                      @RequestParam(value = "idPic", required = false) MultipartFile idPic) throws Exception {
        String idPicPath = null;
        // 判断文件是否为空
        if (!idPic.isEmpty()){
            String path ="D:\\y2\\作业\\ssm_2\\cvs\\web\\statics\\img\\" + File.separator + "uploadFiles";
            //request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadFiles");
            logger.info("SysUserController->add: 上传文件路径" + path);
            String originalFile = idPic.getOriginalFilename();      // 原文件名
            logger.info("SysUserController->add: 原文件名为: " + originalFile);
            String prefix = FilenameUtils.getExtension(originalFile);       // 原文件后缀
            logger.info("SysUserController->add: 原文件后缀为: " + prefix);
            int filesize = 500000;
            logger.info("SysUserController->add: 文件大小: " + idPic.getSize());
            if (idPic.getSize() > filesize) {        // 上传大小不能超过500KB
                request.setAttribute("uploadFileError", "*上传大小不得超过500KB");
                //return "redirect:/user/toAdd";
                return "sysUser/add";
            }else if (prefix.equalsIgnoreCase("jsp") || prefix.equalsIgnoreCase("png")
                      || prefix.equalsIgnoreCase("jpeg")
                      || prefix.equalsIgnoreCase("pneg")) {      // 上传图片格式正确
                String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                logger.info("SysUserController->add: 新生成的文件名称为: " + fileName);
                File targetFile = new File(path);
                if (!targetFile.exists()){
                    targetFile.mkdirs();
                }
                // 保存
                try{
                    idPic.transferTo(new File(targetFile, fileName));
                }catch (Exception e){
                    e.printStackTrace();
                    request.setAttribute("uploadFileError","上传失败!");
                    //return "redirect:/user/toAdd";
                    return "sysUser/add";
                }
                idPicPath = File.separator + "statics" + File.separator + "uploadFiles" + File.separator + fileName;
            }else{
                request.setAttribute("uploadFileError","上传图片格式不正确");
                //return "redirect:/user/toAdd";
                return "sysUser/add";
            }
        }
        sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        sysUser.setIdPicPath(idPicPath);
        if (sysUserService.add(sysUser)){
            return "redirect:/user/list";
        }
        //return "redirect:/user/toAdd";
        return "sysUser/add";
    }*/

    // 添加用户包括多文件上传
    @PostMapping("/add")
    public String add(SysUser sysUser, HttpSession session, HttpServletRequest request,
                      @RequestParam(value = "attachs", required = false) MultipartFile[] attachs) throws Exception {
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = "D:\\y2\\作业\\ssm_2\\cvs\\web\\statics\\" + File.separator + "uploadFiles";
        //request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadFiles");
        logger.info("文件储存路径: " + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()){
                if (i == 0){
                    errorInfo = "uploadFileError";
                }else if (i == 1){
                    errorInfo = "uploadWpError";
                }
                String originalFile = attach.getOriginalFilename();      // 原文件名
                logger.info("SysUserController->add: 原文件名为: " + originalFile);
                String prefix = FilenameUtils.getExtension(originalFile);       // 原文件后缀
                logger.info("SysUserController->add: 原文件后缀为: " + prefix);
                int filesize = 500000;
                logger.info("SysUserController->add: 文件大小: " + attach.getSize());
                if (attach.getSize() > filesize) {       // 上传大小不能超过500KB
                    request.setAttribute(errorInfo, "*上传大小不得超过500KB");
                    flag = false;
                }else if (prefix.equalsIgnoreCase("jsp") || prefix.equalsIgnoreCase("png")
                        || prefix.equalsIgnoreCase("jpeg")
                        || prefix.equalsIgnoreCase("pneg")) {      // 上传图片格式正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                    logger.info("SysUserController->add: 新生成的文件名称为: " + fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    // 保存
                    try {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute(errorInfo, "上传失败!");
                        flag = false;
                    }
                    if (i == 0){
                        idPicPath = File.separator + "statics" + File.separator + "uploadFiles" + File.separator + fileName;
                    }else if (i == 1){
                        workPicPath = File.separator + "statics" + File.separator + "uploadFiles" + File.separator + fileName;
                    }
                    logger.info("证件照: " + idPicPath);
                    logger.info("工作证件照: " + workPicPath);
                }else{
                    request.setAttribute(errorInfo,"* 上传图片格式不正确");
                    flag = false;
                }
            }
        }
        if (flag){
            sysUser.setCreatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
            sysUser.setIdPicPath(idPicPath);
            sysUser.setWorkPicPath(workPicPath);
            if (sysUserService.add(sysUser)){
                return "redirect:/user/list";
            }
        }
        return "sysUser/add";
    }

    // 查询用户详情跳转
   /* @GetMapping("/view/{id}")
    //@GetMapping("/{id}")
    //@GetMapping("/{id}/view")
    public String view(@PathVariable Integer id, Model model) throws Exception {
        logger.debug("SysUserController->view: 根据id查询用户详情" + id);
        SysUser sysUser = sysUserService.getUserById(id);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }*/

    // 查询用户详情json
    @ResponseBody
    @GetMapping(value = "/{id}/view",produces = {"application/json;charset=UTF-8"})
    public Object view(@PathVariable Integer id){
        logger.info("SysUserController->view: 根据id查询用户详情id: " + id);
        SysUser sysUser = null;
        List<SysRole> sysRoleList = new ArrayList<>();
        try{
            sysUser = sysUserService.getUserById(id);

            sysRoleList = sysRoleService.getRoleList();
                    //getNotInRoleName(sysUser.getRoleIdName());
            logger.info("查询到的用户信息: " + sysUser);
        } catch (Exception e) {
            e.printStackTrace();
            return "failed";
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sysUser",sysUser);
        map.put("sysRoleList",sysRoleList);
        return map;
    }

    // 跳转到用户修改信息页面
    @GetMapping("/toUpdate")
    public String toUpdate(@RequestParam Integer uid, Model model) throws Exception {
        logger.info("SysUserController->toUpdate: 跳转到用户修改信息页面");
        SysUser sysUser = sysUserService.getUserById(uid);
        List<SysRole> sysRoleList = new ArrayList<>();
        sysRoleList = sysRoleService.getNotInRoleName(sysUser.getRoleIdName());
        model.addAttribute(sysUser);
        model.addAttribute(sysRoleList);
        return "sysUser/update";
    }

    // 修改用户信息
    @PostMapping("/update")
    public String update(SysUser sysUser, HttpSession session) throws Exception {
        logger.info("SysUserController->update修改用户信息");
        sysUser.setUpdatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        if (sysUserService.update(sysUser)){
            return "redirect:/user/list";
        }
        return "sysUser/update";
    }

    @ResponseBody
    @GetMapping("/userExist")
    public Object userExist(@RequestParam(value = "account") String accont) throws Exception {
        logger.info("SysUserController->userExist 验证用户名account= " + accont + " 的用户是否存在");
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isNullOrEmpty(accont)){
            resultMap.put("exist",1);
        }else{
            SysUser sysUser = sysUserService.getByAccount(accont);
            if (null != sysUser){
                resultMap.put("exist", 1);
            }else{
                resultMap.put("exist", 0);
            }
        }
        return JSON.toJSONString(resultMap);
    }

    // 跳转至修改密码页面
    @GetMapping("/toUpdatePwd")
    public String toUpdatePwd(){
        return "sysUser/updatePassword";
    }

    @ResponseBody
    @PostMapping("/checkOldPwd")
    public Object checkOldPwd(@RequestParam String oldPassword, HttpSession session){
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isNullOrEmpty(oldPassword)){
            resultMap.put("result","error");
        }else if (null == session){
            resultMap.put("result","sessionerror");
        }else{
            int id = ((SysUser)session.getAttribute(Constants.USER_SESSION)).getId();
            SysUser sysUser = sysUserService.getIsPwd(id,oldPassword);
            if (null != sysUser){
                resultMap.put("result","true");
            }else{
                resultMap.put("result","false");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    @PostMapping("/savePassword")
    public String savePassword(String newPassword,HttpSession session, HttpServletRequest request) throws Exception {
        Integer id = ((SysUser)session.getAttribute(Constants.USER_SESSION)).getId();
        boolean result = sysUserService.updatePwd(id, newPassword);
        if (result){
            return "redirect:/user/toLogin";
        }else{
            request.setAttribute("message","修改密码失败");
            return "sysUser/updatePassword";
        }
    }
}
